import A from 'axios'
import store from '@/store/index';
import router from '@/router'

import { Toast } from 'vant';
import { getToken } from '@/utils/auth'

let loading;
let needLoadingRequestCount = 0;
const service = A.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000,
  withCredentials: true,
  cancelToken: new A.CancelToken(c => (A.requestCancel = c))
});
service.interceptors.request.use(config => {
  loading = Toast.loading({
    duration: 0,
    message: '加载中...',
    forbidClick: true,
    // overlay: true
  });
  needLoadingRequestCount++;

  if (store.getters.token) {
    config.headers['Authorization'] = getToken();
  }
  return config;
}, error => {
  Promise.reject(error)
});

service.interceptors.response.use(
  async response => {
    needLoadingRequestCount--;
    if (needLoadingRequestCount == 0) {
      // console.log(needLoadingRequestCount)
    }
    let res = response.data;
    // console.log(res)

    if (res.code !== 0) {
      if (res.code == 401 || res.code == 1007) {
        await store.dispatch('user/logout');
        router.push('/login');
        return Promise.reject(res);
      }
      Toast(res.msg);
      return Promise.reject(res);
    }
    Toast.clear();
    return response.data;
  },
  error => {
    needLoadingRequestCount--;
    if (needLoadingRequestCount == 0) {
      loading.clear();
    }
    // Message.closeAll();

    Toast('网络好像开小差了，请检查网络后重试');
    return Promise.reject(error);
  }
);

export default service;
